package GDoc::Job::Template;

use lib '/govdoc/app/lib';

use Moose;

use File::Spec::Functions 'catfile', 'catdir';
use YAML::XS;
use Template;
use Data::Dumper;
use Getopt::Long;

use GDoc::Logger;
use GDoc::AWS '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_KEY';
use GDoc::Const 'SITE_CONF';
use GDoc::Agency;
use GDoc::Listing;

has logger  => ( is        => 'ro',
                 init_arg  => undef,
                 default   => sub { GDoc::Logger->get_logger }
               );

has ttpath  => ( is        => 'ro',
                 init_arg  => undef,
                 default   => '/govdoc/app/tmpl'
               );

has htdocs  => ( is        => 'ro',
                 init_arg  => undef,
                 default   => '/govdoc/app/htdocs'
               );


my %TMPL_MAP = ( listing               => 'listing',
                 listing_yearly        => 'listing',
                 listing_congressional => 'listing',
                 agency                => 'agency'
               );

sub run { 
    my $self = shift;

    # this should accept params from SQS and not just the cmdline
    my $start_path = '/';
    my $res = GetOptions( 'root=s' => \$start_path );

    $self->logger->info( "Loading config" );
    my $conf = do { 
        local $/;
        open my $fh, '<', SITE_CONF or die "Can't open " . SITE_CONF . " $!";
        YAML::XS::Load( <$fh> );
    };

    my @items = @$conf;
    my %smap  = map { $_->{index} => $_ } @$conf;
    while( my $item = shift @items ) { 
        next unless $item->{index} =~ /^$start_path/;

        my @add_items;
        my $type = $item->{type};
        $self->logger->info( "Processing $type $item->{index}" );
        my $obj;
        if ( $type eq 'agency' ) {  
            $obj = GDoc::Agency->new( $item )
        } elsif ( $type eq 'listing' ) { 
            $obj = GDoc::Listing->new( $item );
        } elsif ( $type eq 'listing_yearly' ) { 
            $obj = GDoc::Listing->new( $item );
            @add_items = $self->make_year_items( $obj );
        } elsif ( $type eq 'listing_congressional' ) { 
            $obj = GDoc::Listing->new( $item );
            @add_items = $self->make_congress_items( $obj );
        } else { 
            die "Invalid item type $type";
        }

        my $tt = Template->new( { INCLUDE_PATH => $self->ttpath,
                                  OUTPUT_PATH  => $self->htdocs,
                                  OUTPUT       => $obj->output
                                }
                              );

        $tt->process( $TMPL_MAP{$type} . '.tmpl', { $TMPL_MAP{$type} => $obj } ) or die $tt->error;

        push @items, @add_items;
        $smap{$_->{index}} = $_ for @add_items;
    }              

    my $stree = $self->make_site_map( \%smap );
    my $smtt = Template->new( { INCLUDE_PATH => $self->ttpath,
                                OUTPUT_PATH  => $self->htdocs,
                                OUTPUT       => '/us/sitemap.html'
                              }
                            );

    $smtt->process( 'sitemap.tmpl', { stree => $stree, smap => \%smap } ) or die $smtt->error;
}


sub make_year_items { 
    my $self = shift;
    my $lst  = shift;

    my @new_confs;
    foreach my $year( $lst->years ) { 
        my %conf = ( type        => 'listing',
                     name        => $lst->name . ', ' . $year,
                     desc        => $lst->desc,
                     parent_type => 'listing_yearly',
                     prefix      => $lst->prefix . '-' . $year,
                     output      => sprintf( $lst->year_output, $year ),
                     index       => sprintf( $lst->year_index,  $year )
                   );

        push @new_confs, \%conf;
    }

    return @new_confs;
}


sub make_congress_items { 
    my $self = shift;
    my $lst  = shift;

    my @new_confs;
    foreach my $congress( $lst->congresses ) {
        # each congress lasts two years, starting in 1789.
        my $year = 1789 + ( 2 * ( $congress - 1) );
        my %conf = ( type        => 'listing',
                     name        => sprintf( '%s, %sth Congress (%04d-%04d)', $lst->name, $congress, $year, $year+1 ),
                     desc        => $lst->desc,
                     parent_type => 'listing_congressional',
                     prefix      => $lst->prefix . '-' . $congress,
                     output      => sprintf( $lst->congress_output, $congress ),
                     index       => sprintf( $lst->congress_index, $congress )
                   );

        push @new_confs, \%conf;
    }

    return @new_confs;
}


sub make_site_map { 
    my $self = shift;
    my %map = %{ +shift };
    my $root = shift || '/us';

    return { map { $_ => $self->make_site_map( \%map, $_ ) } grep { m{^$root/\w+$} } keys %map };
}


    


__PACKAGE__->new->run unless caller;

1;

    
